package com.student_exam_system.service.impl;

import com.student_exam_system.Util.DataUtil;
import com.student_exam_system.Util.MybatisUtils;
import com.student_exam_system.dao.PaperMapper;
import com.student_exam_system.dao.QuestionMapper;
import com.student_exam_system.pojo.Paper;
import com.student_exam_system.service.PaperService;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.transaction.Transaction;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import java.util.List;
import java.util.Map;
/**
 * @author fire'ge
 */
@Service("paperServiceImpl")
public class PaperServiceImpl implements PaperService {
    protected volatile boolean defaultAutoCommit = true;
    final
    PaperMapper paperMapper;

    public PaperServiceImpl(PaperMapper paperMapper) {
        this.paperMapper = paperMapper;
    }

    public PaperMapper getPaperMapper() {
        return paperMapper;
    }

    @Override
    public List<Paper> queryPaperByUserId(int userId) {
        return paperMapper.queryPaperByUserId(userId);
    }

    @Override
    public List<Paper> queryPaperAll() {
        return paperMapper.queryAllPaper();
    }

    @Override
    public Paper queryPaperById() {
        return null;
    }


    private final SqlSession session = MybatisUtils.getSession();
    private final QuestionMapper questionMapper = session.getMapper(QuestionMapper.class);
    private final DataUtil dataUtil = new DataUtil();


    @Transactional(isolation = Isolation.READ_COMMITTED, propagation = Propagation.REQUIRED,rollbackFor = Exception.class)
    @Override
    public List<Map<Integer, String>> selectPaperName() {
        try {
            return paperMapper.selectAllPaperName();
        }catch (Exception e) {
            e.printStackTrace();
        }finally {
            MybatisUtils.closeSession(session);
        }
        return null;
    }


    @Transactional(isolation = Isolation.READ_COMMITTED, propagation = Propagation.REQUIRED,rollbackFor = Exception.class)
    @Override
    public List<Paper> showPaperDetails(int paperId) {
        try {
            //这个paperId是显示paperName时在前端隐形存在
            return paperMapper.selectAllPaper(paperId);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            MybatisUtils.closeSession(session);
        }
        return null;
    }


    @Transactional(propagation= Propagation.REQUIRED,rollbackFor = Exception.class,timeout = 1)
    @Override
    public int newPaper(String paperName,int teacherId, List<Integer> questionId,int choice,int number) {
        //先创建一张空试卷
        Paper paper = new Paper();
        String time = dataUtil.makeTime();
        paper.setPaperName(paperName);
        paper.setPaperDateTime(time);
        paper.setPaperTeacher(teacherId);
        System.out.println(paper);
        try {
            if (choice == 1) {
                //手动出卷
                try {

                    int res1 = paperMapper.newPaper(paper.getPaperName(),paper.getPaperTeacher(),paper.getPaperDateTime());
                    int paperId = paperMapper.getPaperId(paperName,teacherId,time);
                    System.out.println(paperId);
                    //根据前端页面中被选中的试题id逐一插入paper_question表中，形成关系
                    int res2 = 0;
                    for (int i = 0; i < questionId.size(); i++) {
                        questionMapper.addQtoP(paperId,questionId.get(i));
                    }
//                    for (Integer integer : questionId) {
//                        res2 = res2 + questionMapper.addQtoP(paperId, integer);
//                    }
                    System.out.println(res2);
                    return res1 + res2;
                } catch (Exception e) {
                    throw new RuntimeException();
                    //手动提交事务回滚


                }

            } else if (choice == 2) {
                //自动出卷
                try {
                    //先创建一张空试卷
                    int res1 = paperMapper.addPaper(paper);
                    int paperId = paper.getPaperId();
                    int res2 = 0;
                    //随机获得的试题总条数【假设数据库中的试题不会被删除，毕竟这种事只有后台管理可以干】
                    List<Integer> list = questionMapper.questionIds(number);
                    for (Integer integer : list) {
                        res2 = res2 + questionMapper.addQtoP(paperId, integer);
                    }
                    return res2 + res1;
                } catch (Exception e) {
                    throw new RuntimeException();

                    // 返回0：表示的是出试卷失败
//                    return 0;
                }
            }

        }catch (Exception e) {
            e.printStackTrace();
        }finally {

            MybatisUtils.closeSession(session);
        }
        // -1表示相关数据出错
        return -1;
    }


    @Transactional(isolation = Isolation.READ_COMMITTED, propagation = Propagation.REQUIRED,rollbackFor = Exception.class)
    @Override
    public int putInPaper(int paperId, int studentId,int classId) {
        int i =0;
        try {
            String start = paperMapper.getStartTime(paperId, classId);
            Integer time = paperMapper.getTime(paperId, classId);
            DataUtil du = new DataUtil();
            String end = du.changeTime(start, time);
            boolean b = DataUtil.checkTime(end);
            if (!b && (paperMapper.getPaperStatus(studentId,paperId) == 0)) {
                //考试截止的时间比系统时间小，自动提交【只有当考生不主动提交时才会提交】，且该试卷的提交状态为0
                i = paperMapper.putInPaper(paperId, studentId);
            }
        }catch (Exception e) {
            e.printStackTrace();
        }finally {
            MybatisUtils.closeSession(session);
        }
        return i;
    }
}
